import { useState, useEffect } from 'react';

type BrowserInfo = {
  isSupported: boolean;
  browser?: 'chrome' | 'firefox' | 'safari' | 'edge' | 'opera' | 'other';
  version?: number;
};

const MIN_VERSIONS = {
  chrome: 92,
  firefox: 90,
  safari: 17,
  edge: 92,
  opera: 78
} as const;

export const useBrowserCompatibility = (): BrowserInfo => {
  const [browserInfo, setBrowserInfo] = useState<BrowserInfo>({ isSupported: false });

  useEffect(() => {
    if (typeof window === 'undefined') return;

    const ua = navigator.userAgent.toLowerCase();
    let browser: BrowserInfo['browser'] = 'other';
    let version = 0;

    if (ua.includes('edg/')) {
      browser = 'edge';
      version = parseFloat(ua.split('edg/')[1]);
    } else if (ua.includes('opera') || ua.includes('opr/')) {
      browser = 'opera';
      version = parseFloat((ua.match(/(?:opera|opr)\/(\d+\.\d+)/) || [])[1] || '0');
    } else if (ua.includes('chrome')) {
      browser = 'chrome';
      version = parseFloat(ua.split('chrome/')[1]);
    } else if (ua.includes('safari')) {
      browser = 'safari';
      const versionMatch = ua.match(/version\/(\d+\.\d+)/);
      version = versionMatch ? parseFloat(versionMatch[1]) : 0;
    } else if (ua.includes('firefox')) {
      browser = 'firefox';
      version = parseFloat(ua.split('firefox/')[1]);
    }

    const featureSupported = (() => {
      try {
        new RegExp('(?<compatcheck>^)');
        return true;
      } catch {
        return false;
      }
    })();

    const isSupported = browser === 'other'
      ? featureSupported  // 未知浏览器使用特征检测
      : version >= MIN_VERSIONS[browser];

    setBrowserInfo({
      isSupported,
      browser,
      version
    });
  }, []);

  return browserInfo;
};